<!--
  * 考勤
  *
  * @Author:    wy
  * @Date:      2024-09-25 17:09:55
  * @Copyright  <a href="https://1024lab.net">1024创新实验室</a>
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <!-- <a-form-item label="姓名"
                   class="smart-query-form-item">
        <a-select v-model:value="queryForm.userId"
                  size="default"
                  style="width: 200px"
                  :options="formattedOptions"
                  placeholder="姓名"></a-select>
      </a-form-item> -->
      <a-form-item label="考勤月份"
                   class="smart-query-form-item">
        <!-- <a-range-picker v-model:value="queryForm.userCheckTime" :presets="defaultTimeRanges" style="width: 250px" @change="onChangeUserCheckTime" /> -->
        <a-month-picker v-model:value="mon"
                        placeholder="请选择月份"
                        @change="onChangeUserCheckTime" />
      </a-form-item>
      <!-- <a-form-item label="考勤组ID"
                   class="smart-query-form-item">
        <a-input style="width: 150px"
                 v-model:value="queryForm.groupId"
                 placeholder="考勤组ID" />
      </a-form-item> -->
      <!-- <a-form-item label="打卡结果"
                   class="smart-query-form-item">
        <a-select v-model:value="queryForm.timeResult"
                  style="width: 200px"
                  placeholder="打卡结果">
          <a-select-option value="Normal">正常</a-select-option>
          <a-select-option value="Early">早退</a-select-option>
          <a-select-option value="Late">迟到</a-select-option>
          <a-select-option value="SeriousLate">严重迟到</a-select-option>
          <a-select-option value="Absenteeism">旷工迟到</a-select-option>
          <a-select-option value="NotSigned">未打卡</a-select-option>
        </a-select>
        <a-input style="width: 150px"
                 v-model:value="queryForm.timeResult"
                 placeholder="打卡结果" />
      </a-form-item> -->
      <!-- <a-form-item label="位置结果"
                   class="smart-query-form-item">
        <a-select v-model:value="queryForm.locationResult"
                  style="width: 200px"
                  placeholder="位置结果">
          <a-select-option value="Normal">范围内</a-select-option>
          <a-select-option value="Outside">范围外</a-select-option>
          <a-select-option value="NotSigned">未打卡</a-select-option>
        </a-select>
        <a-input style="width: 150px"
                 v-model:value="queryForm.locationResult"
                 placeholder="位置结果" />
      </a-form-item> -->
      <!-- <a-form-item label="考勤类型"
                   class="smart-query-form-item">
        <a-select v-model:value="queryForm.checkType"
                  style="width: 200px"
                  placeholder="考勤类型">
          <a-select-option value="OnDuty">上班</a-select-option>
          <a-select-option value="OffDuty">下班</a-select-option>
        </a-select>
        <a-input style="width: 150px"
                 v-model:value="queryForm.checkType"
                 placeholder="考勤类型" />
      </a-form-item> -->
      <a-form-item class="smart-query-form-item">
        <a-button type="primary"
                  @click="query">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery"
                  class="smart-margin-left10">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>

  <div style="display:flex">
    <a-card size="small"
            :bordered="false"
            :hoverable="true"
            style="width:25%;margin-right:0.5%">
      <div style="text-align:center;margin-top:20px;">{{userStore.$state.actualName}}您好：{{queryForm.month}}月考勤详情如下</div>
      <div style="display:flex;margin-top:30px;">
        <p style="margin-left: 40px;">迟到：{{queryForm.late}}次</p>
        <p style="margin-left: 80px;">出勤：{{queryForm.attendanceDays}}天</p>
      </div>
      <div style="display:flex;margin-top:10px;">
        <p style="margin-left: 40px;">早退：{{queryForm.early}}次</p>
        <p style="margin-left: 80px;">旷工：{{queryForm.absenceDays}}天</p>
      </div>
      <div style="display:flex;margin-top:10px;">
        <p style="margin-left: 40px;">缺卡：{{queryForm.notSigned}}次</p>
      </div>
    </a-card>
    <!---------- 查询表单form end ----------->
    <a-card size="small"
            :bordered="false"
            :hoverable="true"
            style="width:75%">
      <!---------- 表格操作行 begin ----------->
      <!-- <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="showForm"
                  type="primary"
                  size="small">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>
        <a-button @click="confirmBatchDelete"
                  type="danger"
                  size="small"
                  :disabled="selectedRowKeyList.length == 0">
          <template #icon>
            <DeleteOutlined />
          </template>
          批量删除
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns"
                       :tableId="null"
                       :refresh="queryData" />
      </div>
    </a-row> -->
      <!---------- 表格操作行 end ----------->

      <!---------- 表格 begin ----------->
      <a-table size="small"
               :dataSource="tableData"
               :columns="columns"
               rowKey="id"
               bordered
               :loading="tableLoading"
               :pagination="false">

        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'employeeEntity'">
            <span>{{record.employeeEntity.actualName}}</span>
          </template>
          <template v-if="column.dataIndex === 'checkData'">
            <span>{{record.checkData.split(' ')[0]}}</span>
          </template>
          <template v-if="column.dataIndex === 'morning'">
            {{getResult(record.morning)}}
          </template>
          <template v-if="column.dataIndex === 'noon'">
            {{getResult(record.noon)}}
          </template>
          <template v-if="column.dataIndex === 'afternoon'">
            {{getResult(record.afternoon)}}
          </template>
          <template v-if="column.dataIndex === 'evening'">
            {{getResult(record.evening)}}
          </template>
          <template v-if="column.dataIndex === 'checkType'">
            {{ record.checkType === 'OnDuty' ? '上班' : '下班' }}
          </template>
          <template v-if="column.dataIndex === 'timeResult'">
            {{ getTimeResultText(record.timeResult) }}
          </template>
          <template v-if="column.dataIndex === 'locationResult'">
            {{getLocationResult(record.locationResult)}}
          </template>
          <template v-if="column.dataIndex === 'action'">

            <div class="smart-table-operate">
              <a-button @click="showForm(record)"
                        type="link">详情</a-button>
              <!-- <a-button @click="onDelete(record)"
                        danger
                        type="link">删除</a-button> -->
            </div>
          </template>
        </template>
      </a-table>
      <!---------- 表格 end ----------->

      <div class="smart-query-table-page">
        <a-pagination showSizeChanger
                      showQuickJumper
                      show-less-items
                      :pageSizeOptions="PAGE_SIZE_OPTIONS"
                      :defaultPageSize="queryForm.pageSize"
                      v-model:current="queryForm.pageNum"
                      v-model:pageSize="queryForm.pageSize"
                      :total="total"
                      @change="queryData"
                      @showSizeChange="queryData"
                      :show-total="(total) => `共${total}条`" />
      </div>

      <AttendanceForm ref="formRef"
                      @reloadList="queryData" />

    </a-card>
  </div>
</template>
<script setup>
import { reactive, ref, onMounted, computed, defineComponent } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { SmartLoading } from '/@/components/framework/smart-loading';
import { attendanceApi } from '/@/api/business/attendance/attendance-api';
import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
import { smartSentry } from '/@/lib/smart-sentry';
import TableOperator from '/@/components/support/table-operator/index.vue';
import { defaultTimeRanges } from '/@/lib/default-time-ranges';
import AttendanceForm from './attendance-form.vue';
import { dictApi } from '/@/api/support/dict-api';
import { useUserStore } from '/@/store/modules/system/user';
import { employeeApi } from '/src/api/system/employee-api';
// ---------------------------- 表格列 ----------------------------

const mon = ref()

const columns = ref([
  // {
  //     title: 'id',
  //     dataIndex: 'id',
  //     ellipsis: true,
  // },
  //   {
  //     title: '用户ID',
  //     dataIndex: 'userId',
  //     ellipsis: true,
  //   },
  {
    title: '姓名',
    dataIndex: 'employeeEntity',
    ellipsis: true,
  },
  {
    title: '打卡日期',
    dataIndex: 'checkData',
    ellipsis: true,
  },
  {
    title: '早上打卡',
    dataIndex: 'morning',
    ellipsis: true,
  },
  {
    title: '中午打卡',
    dataIndex: 'noon',
    ellipsis: true,
  },
  {
    title: '下午打卡',
    dataIndex: 'afternoon',
    ellipsis: true,
  },
  {
    title: '晚上打卡',
    dataIndex: 'evening',
    ellipsis: true,
  },
  //   {
  //     title: '考勤组ID',
  //     dataIndex: 'groupId',
  //     ellipsis: true,
  //   },
  //   {
  //     title: '打卡结果',
  //     dataIndex: 'timeResult',
  //     ellipsis: true,
  //   },
  //   {
  //     title: '位置结果',
  //     dataIndex: 'locationResult',
  //     ellipsis: true,
  //   },
  // {
  //     title: '审批流程实例ID',
  //     dataIndex: 'procInstId',
  //     ellipsis: true,
  // },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 90,
  },
]);

// ---------------------------- 查询数据表单和方法 ----------------------------
// 获取当前日期
const currentDate = new Date();
// 获取当前月份
let currentMonth = (currentDate.getMonth() + 1).toString().padStart(2, '0'); // 0-11 (0表示1月)
const currentYear = currentDate.getFullYear(); // 获取当前年份

const queryFormState = {
  userId: undefined,//用户id
  userCheckTime: [], //实际打卡时间
  userCheckTimeBegin: currentYear + '-' + currentMonth + '-01 00:00:00', //实际打卡时间 开始
  userCheckTimeEnd: currentYear + '-' + currentMonth + '-31 23:59:59', //实际打卡时间 结束
  groupId: undefined, //考勤组ID
  timeResult: undefined, //打卡结果
  locationResult: undefined, //位置结果
  checkType: undefined, //考勤类型
  pageNum: 1,
  pageSize: 10,
  employeeEntity: {
    actualName: undefined,
  },
  month: currentMonth,
  early: 0,//早退
  late: 0,//迟到
  notSigned: 0,//未打卡
  attendanceDays: 0,//出勤天数
  absenceDays: 0,//缺勤天数
};
// 查询表单form
const queryForm = reactive({ ...queryFormState });
// 表格加载loading
const tableLoading = ref(false);
// 表格数据
const tableData = ref([]);
// 总数
const total = ref(0);

// 重置查询条件
function resetQuery () {
  mon.value = undefined
  let pageSize = queryForm.pageSize;
  Object.assign(queryForm, queryFormState);
  queryForm.pageSize = pageSize;
  queryData();
}

const actualNameOptions = ref([])

//查询按钮
function query () {
  queryForm.pageNum = 1;
  queryData();
}

// 查询数据
async function queryData () {
  tableLoading.value = true;
  try {
    const form = {
      employeeId: userStore.employeeId,
    };
    //获取登录用户信息
    const data = await employeeApi.queryWeather(form);
    queryForm.userId = data.userId
    let queryResult = await attendanceApi.queryData(queryForm);
    tableData.value = queryResult.data.list;
    total.value = queryResult.data.total;
    let result = await attendanceApi.queryResult(queryForm)
    if (result.data != null) {
      queryForm.early = result.data.early
      queryForm.late = result.data.late
      queryForm.attendanceDays = result.data.attendanceDays
      queryForm.absenceDays = result.data.absenceDays
      queryForm.notSigned = result.data.notSigned
    } else {
      queryForm.early = 0
      queryForm.late = 0
      queryForm.attendanceDays = 0
      queryForm.absenceDays = 0
      queryForm.notSigned = 0
    }
    queryForm.month = queryForm.userCheckTimeBegin.substring(5, 7)
    //查询员工数据
    let res = await dictApi.ProjecPersonid();
    actualNameOptions.value = res.data.filter(a => a.userId != '' && a.userId != null)
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}

const formattedOptions = computed(() => {
  return actualNameOptions.value.map(user => ({
    label: user.actualName, // 显示的文本
    value: user.userId      // 选项的 key
  }));
});

function onChangeUserCheckTime (dates, dateStrings) {
  queryForm.userCheckTimeBegin = dateStrings + '-01 00:00:00';
  queryForm.userCheckTimeEnd = dateStrings + '-31 23:59:59';
}

const userStore = useUserStore();

onMounted(queryData);

// ---------------------------- 添加/修改 ----------------------------
const formRef = ref();

function showForm (data) {
  formRef.value.show(data);
}

// ---------------------------- 单个删除 ----------------------------
//确认删除
function onDelete (data) {
  Modal.confirm({
    title: '提示',
    content: '确定要删除选吗?',
    okText: '删除',
    okType: 'danger',
    onOk () {
      requestDelete(data);
    },
    cancelText: '取消',
    onCancel () { },
  });
}

//请求删除
async function requestDelete (data) {
  SmartLoading.show();
  try {
    let deleteForm = {
      goodsIdList: selectedRowKeyList.value,
    };
    await attendanceApi.delete(data.id);
    message.success('删除成功');
    queryData();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}

// ---------------------------- 批量删除 ----------------------------

// 选择表格行
const selectedRowKeyList = ref([]);

function onSelectChange (selectedRowKeys) {
  selectedRowKeyList.value = selectedRowKeys;
}

// 批量删除
function confirmBatchDelete () {
  Modal.confirm({
    title: '提示',
    content: '确定要批量删除这些数据吗?',
    okText: '删除',
    okType: 'danger',
    onOk () {
      requestBatchDelete();
    },
    cancelText: '取消',
    onCancel () { },
  });
}

//请求批量删除
async function requestBatchDelete () {
  try {
    SmartLoading.show();
    await attendanceApi.batchDelete(selectedRowKeyList.value);
    message.success('删除成功');
    queryData();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}
//打卡结果列表转换
function getTimeResultText (checkType) {
  switch (checkType) {
    case 'Normal':
      return '正常';
    case 'Early':
      return '早退';
    case 'Late':
      return '迟到';
    case 'SeriousLate':
      return '严重迟到';
    case 'Absenteeism':
      return '旷工迟到';
    case 'NotSigned':
      return '未打卡';
    default:
      return '未知状态';
  }
}

//位置结果列表转换
function getLocationResult (locationResult) {
  switch (locationResult) {
    case 'Normal':
      return '范围内';
    case 'Outside':
      return '范围外';
    case 'NotSigned':
      return '未打卡';
    default:
      return '未知状态';
  }
}

function getResult (result) {
  switch (result) {
    case 1:
      return '正常';
    case 2:
      return '早退';
    case 3:
      return '迟到';
    case 4:
      return '严重迟到';
    case 5:
      return '旷工迟到';
    case 0:
    case 6:
      return '未打卡';
    default:
      return '未打卡'
  }
}
</script>
